<template>
  <div class="container">
    <div class="card">

      <el-form ref="formRef" :rules="data.rules" :model="data.form"  label-width="80px" style="padding-right: 40px;padding-top: 20px">

        <el-form-item label="头像" prop="avatar">
          <div>
            <el-upload label=""
                       class="avatar-uploader"
                       action="http://localhost:9090/file/upload"
                       :show-file-list="false"
                       :before-upload="beforeAvatarUpload"
                       :on-success="handleAvatarSuccess"
                       :headers="{Authorization:uploadToken.token}"
            >
              <img v-if="data.form.avatar" :src="data.form.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  格式为.jpg/.png,且不超过1mb
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="账号" prop="username">
          <el-input disabled size="large" v-model="data.form.username" placeholder="请输入账号" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input  size="large" v-model="data.form.name" placeholder="请输入姓名" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input size="large" v-model="data.form.phone" placeholder="请输入电话" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input size="large" v-model="data.form.email" placeholder="请输入邮箱" autocomplete="off"></el-input>
        </el-form-item>


        <div style="display:flex;justify-content: center;">
          <el-button size="large" style="width: 30%" type="primary" @click="updateUser">更新</el-button>
          <el-button size="large" style="width: 30%" type="primary" @click="handleUpdatePassword">修改密码</el-button>
        </div>



      </el-form>

      <el-dialog title="修改密码" v-model="data.formVisible1" width="500">
        <el-form ref="formRef" :rules="data.rules" :model="data.form" style="padding-right: 50px;padding-top: 20px">
          <el-form-item  prop="password" label="原密码" label-width="100px">
            <el-input show-password v-model="data.form.password" placeholder="请输入原密码" autocomplete="off"/>
          </el-form-item>
          <el-form-item prop="newPassword" label="新密码" label-width="100px">
            <el-input show-password v-model="data.form.newPassword" placeholder="请输入新密码" autocomplete="off"/>
          </el-form-item>
          <el-form-item prop="rePassword" label="确认新密码" label-width="100px">
            <el-input show-password v-model="data.form.rePassword" placeholder="请再次输入新密码" autocomplete="off" />
          </el-form-item>

        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="data.formVisible1=false">取消</el-button>
            <el-button type="primary" @click="savePassword">保存</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>

</template>

<script setup>
import {reactive,ref} from "vue";
import request from "../../utils/request";
import {ElMessage} from "element-plus";
import {useTokenStore} from "../../stores/token";
const formRef=ref()
const uploadToken = useTokenStore();

// 上传前的钩子函数，可在这里进行文件格式等验证（与后端验证配合）
const beforeUpload = (file)=>{

  if (file.type !== 'image/jpeg' && file.type !== 'image/png'){
    ElMessage.error('图片格式不正确，请上传jpg/png格式的图片!')
    return false
  }
  if (file.size / 1024 / 1024 > 1) {
    ElMessage.error('图片大小不能超过 1MB!')
    return false
  }

  return true
}
const handleAvatarSuccess = (res) => {
  console.log(res.data)
  data.form.avatar = res.data
}


//  //重置 修改密码 表单校验状态
// const  editPasswordClose=()=>{
//
//    this.$refs.formRef.resetFields();
//  }

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请再次确认密码'))
  } else if (value !== data.form.newPassword){
    callback(new Error('两次输入的密码不一致!'))
  } else {
    callback()
  }

}
const data=reactive({
  formVisible1:false,
  user:JSON.parse(localStorage.getItem('localStorageUser')),
  form:{},
  rules:{
    username:[{required:true,message:'请输入账号',trigger:'blur'}],
    name:[{required:true,message:'请输入姓名',trigger:'blur'}],
    phone:[{required:true,message:'请输入电话',trigger:'blur'}],
    email:[{required:true,message:'请输入邮箱',trigger:'blur'}],
    password:[
      {required:true,message:'请输入密码',trigger:'blur'},
      { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
    ],
    newPassword:[
      {required:true,message:'请输入新密码',trigger:'blur'},
      { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
    ],
    rePassword:[{validator:validatePass,required:true,trigger:'blur'}]
  }
})

const emit=defineEmits(['updateUser'])

if (data.user.role==='user'){
  request.get('/user/selectById/' + data.user.id).then(res=>{
    data.form = res.data
  })
}else {
  data.form = data.user
}

const handleUpdatePassword=()=>{
  data.form.password="",
      data.form.newPassword="",
      data.form.rePassword=""
  data.formVisible1=true
}

const savePassword=()=>{
  data.form.id = data.user.id
  data.form.role = data.user.role

  formRef.value.validate((valid) => {
    if (valid){

      request.put('/web/updatePassword', data.form).then(res =>{
        if (res.code === '200'){
          ElMessage.success('操作成功')
          localStorage.removeItem('localStorageUser')
          setTimeout(()=>{
            location.href = '/login'
          },500)
        }else {
          ElMessage.error(res.msg)
        }
      })
    }


  })



}

const updateUser=()=>{
  if (data.user.role==='user'){
    request.put('/user/update', data.form).then(res=>{
      if (res.code==='200'){
        ElMessage.success('更新成功')
        //更新缓存数据
        localStorage.setItem('localStorageUser',JSON.stringify(data.form))
        //触发父级从缓存里拿到的数据
        emit('updateUser')
      }else {ElMessage.error(res.msg)}

    })
  }else if (data.user.role==='admin'){
    request.put('/admin/update', data.form).then(res=>{
      if (res.code==='200'){
        ElMessage.success('更新成功')
        //更新缓存数据
        localStorage.setItem('localStorageUser',JSON.stringify(data.form))
        //触发父级从缓存里拿到的数据
        emit('updateUser')
      }else {ElMessage.error(res.msg)}

    })
  }
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;    /* 垂直居中 */
  height: 80vh;          /* 使容器高度占满整个视口 */
}

.card {
  width: 50%;
  padding: 20px;
}
</style>